<template>
  <div class='workform'>
    <el-form ref='workFormRef' :model='workFormOption' :rules='WorkRules' label-width='100px' size='large'
      @submit.prevent>
      <el-form-item label='类型：' prop='t'>
        <el-radio-group :disabled="isDisabled" v-model='workFormOption.t' class='workstyle'>
          <el-radio :value='0' size='large'>随堂作业</el-radio>
          <el-radio :value='1' size='large'>期末考试</el-radio>
        </el-radio-group>

      </el-form-item>


      <el-form-item label='作业名称：' prop='name'>
        <el-input v-model.trim='workFormOption.name' placeholder='请输入作业名称' />
      </el-form-item>


      <el-form-item label='作业内容：' prop='content'>
        <PubEditor :editContent='workFormOption.content' @editContentEnv='editContentEnv' @imgUrlEnv="imgUrlEnv"
          @videoUrlEnv="videoUrlEnv" placeholder='请认真填写作业要求...'>
        </PubEditor>
      </el-form-item>


      <el-form-item label='大附件' prop='files'>
        <OtherBigFile :fileArr='workFormOption.files' ref='OtherBigFileRef' @fileArrChange='fileArrChange'>
        </OtherBigFile>
      </el-form-item>


      <el-form-item label='结束时间：' prop='end_time'>
        <el-date-picker v-model='workFormOption.end_time' type='datetime' placeholder='选择结束日期'
          :disabledDate='disabledEndDate' />
      </el-form-item>


      <el-form-item label='发布时间：' prop='release_time'>
        <el-radio-group v-model='workFormOption.mode' class='poststyle'>
          <el-radio :disabled="isDisabled" :value='false' size='large'>立即发布</el-radio>
          <el-radio :disabled="isDisabled" :value='true' size='large'>定时发布</el-radio>
        </el-radio-group>

        <template v-if='workFormOption.mode'>
          <el-date-picker v-model='workFormOption.release_time' type='datetime' placeholder='选择日期和时间'
            :disabledDate='disabledReleaseDate' />
        </template>

      </el-form-item>


      <el-form-item>
        <div class='btngroup'>
          <el-button :disabled="btnDisabled" type='primary' @click='submitForm'>
            {{ rowData ? '修改作业' : '创建作业' }}
          </el-button>

          <el-button @click='resetForm'>取消</el-button>
        </div>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { isEditEmpty, parseTime } from '@/utils/common';
import { addWorkRow, upRowWork } from '@/api/banke/zuoye';
import PubEditor from '@/components/PubEditor/index.vue';
import OtherBigFile from '@/components/OtherBigFile/index.vue';
import dayjs from "dayjs";
import counterStore from "@/store/modules/counter";
import _ from 'lodash';
const imgUrlArr = ref([])

const videoUrlArr = ref([])
const { proxy } = getCurrentInstance();

const OtherBigFileRef = ref();
const btnDisabled=ref(false)
const isDisabled = ref(false)
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,

  },
});



const emits = defineEmits(['update:dialogVisible', 'resetData']);
//作业表结构
const workFormOption = ref({
  name: '',       //作业名称
  end_time: '',        //结束时间
  content: '',    //富文本内容
  t: 0,      //作业类型（0/1）
  mode: false,//发布类型  立即发布/定时发布 （true false）
  release_time: null, //发布时间
  files: [],  //大附件数组
  bk_id: counterStore().bkItem.id,
})

watch(() => workFormOption.value.mode, (nv) => {
  console.log(nv);
  if (nv == false) {
    workFormOption.value.release_time = null;
    WorkRules.value.release_time = [];
    proxy.$refs['workFormRef'].clearValidate(['release_time']);
  }else if(nv == true){
    WorkRules.value.release_time = [
      { required: true, message: '定时发布时间必选', trigger: 'change' },
    ];
  }
});
//如果修改传值，修改作业表结构
if (props.rowData) {
  // 过滤掉original_filename包含operation_content的项，解决作业中的文字图像内容在附件中显示
  props.rowData.files = props.rowData.files.filter(file => 
    !file.original_filename.includes('operation_content')
  );

  workFormOption.value = props.rowData

  // 修改作业如果状态是已结束，将作业模式改为立即发布模式，为了解决定时发布，发布完后状态还是已结束的bug
  if(props.rowData.status==2){
    workFormOption.value.mode=false
    workFormOption.value.release_time=null
  }
  
  isDisabled.value = true
  // 回显图像和视频
  workFormOption.value.content = workFormOption.value.content.replace(/\[file_id: (\d+),url: (.+?\.(jpg|png|webp|svg|gif).*?)\]/g, '<img src="$2" alt="[file_id: $1,url: $2]');

  workFormOption.value.content = workFormOption.value.content.replace(/<div data-w-e-type="video" data-w-e-is-void>\s*\[file_id:\s*(\d+),url:\s*([^[\]]+)\]\s*<\/div>/g, '<video poster="[file_id: $1,url: $2]" src="$2"></video>');

    
  // // 去除多余的符号
  workFormOption.value.content = workFormOption.value.content.replace(/>" data-href="?" style="?"\//g, '');
}


console.log(workFormOption.value.content);


//表结构验证规则



const WorkRules = ref({
  t: [
    {
      required: true,
      message: '类型必须选择',
      trigger: 'blur',
    },
  ],
  name: [
    { required: true, message: '作业名称必须填写', trigger: 'blur' },
    { min: 3, max: 30, message: '作业名称需3-30字间', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '作业内容必须填写', trigger: 'blur' },
  ],
  end_time: [
    { required: true, message: '作业结束时间必选', trigger: 'change' },
  ],

});


//大附件内容改变
const fileArrChange = (e) => {
  workFormOption.value.files = e;
};

// 获取上传图像成功的Url
const imgUrlEnv = (e) => {
console.log(e);

  imgUrlArr.value.push(e)
}

// 获取上传视频成功的url

const videoUrlEnv = (e) => {
  videoUrlArr.value.push(e)

}

//获取富文本返回的内容
const editContentEnv = (e) => {
  if (e == '<p><br></p>') {
    e = ''
  }

  
 // 如果 workFormOption.value.content 中的 img 标签包含 file_id，则保留原有的 img 标签
  const existingImages = workFormOption.value.content.match(/<img[^>]*alt="\[file_id:.*?\]"[^>]*>/g) || [];
  e = e.replace(/<img[^>]*>/g, (match) => {
    // 查找匹配的 existingImg
    const existingImg = existingImages.find(img => {
      const srcMatch = img.match(/src="([^"]*)"/);
      const currentSrcMatch = match.match(/src="([^"]*)"/);
      return srcMatch && currentSrcMatch && srcMatch[1] === currentSrcMatch[1];
    });

    // 如果找到匹配的 existingImg，则保留其 alt 属性
    if (existingImg) {
      const altMatch = existingImg.match(/alt="\[file_id:.*?\]"/);
      if (altMatch) {
        return match.replace(/alt="[^"]*"/, altMatch[0]);
      }
    }
    return match;
  });

 

  workFormOption.value.content = e;

  console.log(e);

  if (workFormOption.value.content) {
    proxy.$refs['workFormRef'].clearValidate(['content']);
  }
  // 将上传成功的图像和视频的[file_id: ${res.file_id},url: ${tem_url.value}]地址分别放在alt和poster属性中
 // 新增索引映射函数，建立匹配位置与上传文件的对应关系
 const processMediaAttributes = (content, urlArr, regex, attrName) => {
  let index = 0;
  return content.replace(regex, (match) => {
    // 只替换对应序号的属性值
    if (index < urlArr.value.length) {
      const replacement = `${attrName}="${urlArr.value[index++]}"`;
      return match.replace(/(alt|poster)=".*?"/, replacement);
    }
    return match;
  }); 
};


// 使用示例
if (imgUrlArr.value.length > 0 || videoUrlArr.value.length > 0) {
  // 分步骤处理不同媒体类型
  // 处理图片alt属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    imgUrlArr,
    /<img[^>]*alt="[^"]*"[^>]*>/g,
    "alt"
  );


  // 处理视频poster属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    videoUrlArr,
    /<video[^>]*poster="[^"]*"[^>]*>/g,
    "poster"
  );
}  

console.log(workFormOption.value.content);

};

const disabledEndDate = time => {
  if (time.getTime() < new Date().getTime()) return true
  const release_time = workFormOption.value.release_time
  if (release_time) return dayjs(release_time).isAfter(dayjs(time))
  else return false
}

const disabledReleaseDate = time => {
  if (time.getTime() < new Date().getTime()) return true
  const end_time = workFormOption.value.end_time
  if (end_time) return dayjs(end_time).isBefore(dayjs(time))
  else return false
}
// 作业新增修改核心函数
const handleSubmitForm=()=>{


  // 优化后的正则表达式（增加精准匹配和非贪婪模式）
const imgAltRegex = /<img\b(?=(?:[^>]*?\balt=(["'])(.*?)\1)?)[^>]*>/gmi;
const videoPosterRegex = /<video\b(?=(?:[^>]*?\bposter=(["'])(\[file_id:.*?])"|')?)[^>]*>.*?<\/video>/gmis;

// 调整替换顺序：先处理视频再处理图片
const processRichText = (html) => {
  // 第一阶段：处理视频标签（保留结构）
  const videoProcessed = html.replace(videoPosterRegex, (match, quote, posterJson) => {
    try {
      // 解析JSON格式的poster数据
      const [posterData] = JSON.parse(posterJson);
      return match.replace(posterJson, posterData.url); // 仅替换poster值
    } catch {
      return match; // 解析失败保持原样
    }
  });

  // 第二阶段：处理图片标签（保留结构）
  const imgProcessed = videoProcessed.replace(imgAltRegex, (match, quote, altValue) => {
    return altValue ? match.replace(altValue, altValue.trim()) : match;
  });

  return imgProcessed;
};




// 使用示例
const result = processRichText(workFormOption.value.content);
console.log('安全处理结果:', result);
  proxy.$refs['workFormRef'].validate(valid => {
    if (valid) {
      // 如果点修改传值
      btnDisabled.value=true
    
      if (props.rowData) {

        let filesArr = workFormOption.value.files.map(item => item.file_id);
        workFormOption.value.files = filesArr
        let end_time = null
        let release_time = null
        // 判断时间是否是日期对象
        if (workFormOption.value.end_time instanceof Date) {
          end_time = workFormOption.value.end_time.getTime() + ''
        } else {
          end_time = workFormOption.value.end_time + ''
        }
        // 判断时间是否是日期对象
        if (workFormOption.value.release_time instanceof Date) {
          release_time = workFormOption.value.release_time.getTime() + ''
        } else {
          if (workFormOption.value.release_time) {
            release_time = workFormOption.value.release_time + ''
          } else {
            release_time = null
          }
        }
       
        let options = {
          "id": workFormOption.value.id,
          "name": workFormOption.value.name,
          "content": result,
          "release_time": release_time, // 发布时间  可以为null ，立即发布时
          "end_time": end_time, // 结束时间
          "t": workFormOption.value.t,// 0 作业 1 考试
          "mode": workFormOption.value.mode,//true 立即发布 false定时发布
          "files": workFormOption.value.files,
          "bk_id": workFormOption.value.bk_id// 班课主表的id

        }
        console.log(options);

        upRowWork(options).then(res => {
          console.log(res);
          if (!res) {
            ElMessage.success('修改成功');
            btnDisabled.value=false
            emits('update:dialogVisible', false);
            emits('resetData')
          } else {
            ElMessage.error(res.response.data);
            btnDisabled.value=false

          }
        })
        return

      }

      const { end_time, release_time, mode } = workFormOption.value
      if (mode && (!dayjs(release_time).isBefore(dayjs(end_time)))) {
        ElMessage.warning('发布时间不能在作业结束时间之前')
        btnDisabled.value=false
        return
      }


      let relpeaseTime = workFormOption.value.release_time
      relpeaseTime = relpeaseTime ? relpeaseTime.getTime() + '' : null


      let endTime = String(workFormOption.value.end_time.getTime())

      let filesArr = workFormOption.value.files.map(item => item.file_id);
      workFormOption.value.files = filesArr
      let options = {
        bk_id: workFormOption.value.bk_id,
        content: result,
        end_time: endTime,
        files: workFormOption.value.files,
        mode: workFormOption.value.mode,
        name: workFormOption.value.name,
        release_time: relpeaseTime,
        t: workFormOption.value.t
      }

      console.log(options);

      addWorkRow(options).then(res => {
        if (!res) {
          ElMessage.success('发布作业成功');
          btnDisabled.value=false
          emits('update:dialogVisible', false);
          emits('resetData')
        } else {
          ElMessage.error(res.response.data);
          btnDisabled.value=false
        }
      }).catch(err => {
        console.log(err);
      });
    }
  });

}


// 防抖效果
//提交新增作业表单
const submitForm = _.debounce(handleSubmitForm, 300);




//重置表单
const resetForm = () => {
  proxy.$refs.workFormRef.resetFields();
  emits('update:dialogVisible', false);
};
</script>




<style>
.el-button.is-text {
  /* 隐藏“此刻”按钮，注意这里的类名可能会根据Element Plus的版本有所不同 */
  display: none;
}

.el-upload {
  display: block;
}

.el-upload-dragger {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>

<style lang='scss' scoped>
.myedit {
  width: 100%;
}


.workform {
  padding: 0 30px;

  .fileList {
    display: flex;
    flex-wrap: wrap;

    .item {
      padding-right: 30px;
      display: flex;
      align-items: center;
      font-size: 14px;
      position: relative;

      .coloricon {
        font-size: 18px;
        margin-right: 5px;
      }

      .close {
        font-size: 20px;
        color: #FF5733;
        position: absolute;
        right: 8px;
        top: 0px;
        display: none;
        cursor: pointer;
      }

      &:hover {
        .close {
          display: block;
        }
      }
    }

  }
}

.popCover {
  min-height: 400px;
}

.poststyle {
  margin-right: 20px;
}

.addBan {
  padding: 0 30px;

  .el-form-item {
    padding: 5px 0;
  }

  .cover {
    display: flex;
  }

  .upload {
    width: 200px;
    height: 113px;

    .cover-uploader {
      width: 100%;
      height: 100%;
      border: 1px dashed #ccc;
      border-radius: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      position: relative;
      cursor: pointer;

      .view {
        img {
          width: 100%;
          height: 100%;
          display: block;
        }

        div {
          font-size: 14px;
          color: #999
        }
      }

      .ceng {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;

        .iconfont {
          font-size: 40px;
        }
      }

    }

    .cover-uploader:hover {
      border-color: #4395FF;

      .ceng {
        opacity: 1;
      }
    }
  }

  .text {
    padding-left: 30px;
    line-height: 1.7em;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .top {
      font-size: 16px;
      color: #4395FF;
      cursor: pointer;

      .iconfont {
        font-size: 22px;
        vertical-align: middle;
      }
    }

    .top:hover {
      color: #175CEB;
    }

    .btm {
      font-size: 13px;
      color: #999;
    }
  }

  .btngroup {
    padding-top: 30px;
  }
}
</style>
